
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>


//翻译服务器:
class DictServer
{
public:
    DictServer(int port)
        :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", 9090), 
            "DictServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _server.start();//打开服务器进行能监听;
        _baseloop.loop(); //开始死循环事务监听;
    }
    
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout << "链接建立成功!" << std::endl;
        }
        else
        {
            std::cout << "链接断开" << std::endl;

        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        static std::unordered_map<std::string, std::string> dict_map = 
        {
            {"hello", "你好"},
            {"world", "世界"},
            {"love", "爱"}
        };
        //获取全部字符串;
        std::string msg = buf->retrieveAllAsString();
        std::string res;

        //查找对应单词;
        auto it = dict_map.find(msg);
        if(it != dict_map.end())
        {
            res = it->second;
        }
        else
        {
            res = "未知单词";
        }
        conn->send(res);
    }
private:
    //服务器
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer server(9090);
    server.start();
    return 0;
}